var express = require('express');
var router = express.Router();
const {all} = require("../dao/com_tc_dao");
const {
    createOKResponse, createErrorResponse
} = require('../factories/responses/api');
const usersDao = require('../dao/users');
const jwtFacade = require('../facades/jwt.facade');
const {Client} = require('../utils/sms');
const redis = require('../utils/redis');
/**
 * 获取验证码
 */
router.get('/code/:phone', async function (req, res, next) {
    const phone = req.params.phone
    const r = await Client.main(phone);
    // 保存到 redis
    await redis.set(`login_code_${phone}`, r.code)
    res.json({title: r}).end();
});


/**
 * 验证码和手机号登录
 */
router.post('/login', async function (req, res, next) {
    try {
        // Extract request input:
        const phone = req.body?.phone
        const code = req.body?.code

        console.log(phone, code)
        if (!phone || !code) {
            // If bad input, throw ValidationError:
            const err = new Error("Invalid email OR password input");
            err.name = "ValidationError";
            throw err;
        }

        const [tokens, user] = await usersDao.login({phone, code});

        // Everything's fine, send response.
        res.json({
            code: 0,
            msg: "login succes",
            data: tokens
        }).end()
        // return createOKResponse({
        //     res, content: {
        //         tokens, // Convert user to JSON, to clear sensitive data (like password).
        //         user: user.toJSON()
        //     }
        // });
    } catch (error) {
        console.error("UsersController._login error: ", error);
        return _processError(error, req, res);

    }
});

const _processError = (error, req, res) => {
    // Default error message.
    let errorMessage = error?.message ?? 'Internal server error';
    // Default HTTP status code.
    let statusCode = 500;

    switch (error.name) {
        case('Unauthorized'):
            errorMessage = 'Email or password are incorrect.';
            statusCode = 406;
            break;
        case('ValidationError'):
            errorMessage = "Invalid email OR password input";
            statusCode = 401;
            break;
        case('InvalidToken'):
            errorMessage = 'Invalid token or token expired';
            statusCode = 401;
            break;
        case('UserNotFound'):
            errorMessage = "Such user doesn't exist";
            statusCode = 400;
            break;

        // Perform your custom processing here...

        default:
            break;
    }

    // Send error response with provided status code.
    // return createErrorResponse({
    //     res, error: {
    //         message: errorMessage
    //     }, status: statusCode
    // });
    res.json({
        code: -1,
        msg: errorMessage,
        data: null
    }).end()
}

module.exports = router;
